<template>
  <div id="app">
    <header>
      <el-row>
        <el-button size="small" type="primary" @click="KlineDialogHandle()">换一只</el-button>
        <el-button size="small" type="success" @click="tradeDialogHandle()">交易</el-button>
        <el-button size="small" type="warning" @click="backOne">上一步</el-button>
        <el-button size="small" type="info" @click="passOne">下一步</el-button>

        <el-button size="small" type="warning" @click="settleDialogHandle()">结算</el-button>
        <el-button size="small" type="info" plain class="right" @click="readmeDialogHandle()">说明</el-button>
      </el-row>
    </header>
    <main id="main">
      <Vue-kline :klineParams="klineParams" :klineData="klineData"></Vue-kline>
    </main>
    <!-- 获得K线 dialog -->
    <get-Kline-Dialog ref="getKlineDialog" v-if="KlineDialogVisible" @getData="handleRawData"></get-Kline-Dialog>
    <!-- 交易 dialog -->
    <trade-Dialog @getrateData="handleRateData" ref="tradeDialog" v-if="tradeDialogVisible"></trade-Dialog>
    <readme-Dialog ref="readmeDialog" v-if="readmeDialogVisible"></readme-Dialog>
    <settle-Dialog ref="settleDialog" v-if="settleDialogVisible"></settle-Dialog>
  </div>
</template>

<style>
html,
body {
  height: 100%;
}

/* #app {
  height: 100%;
} */
main {
  height: 100%;
}

header {
  padding: 10px;
  background-color: #f6f6f6;
}

.right {
  float: right;
}
</style>

<script>
import VueKline from "./kline/kline";
import {Chart} from './kline/js/chart'
import getKlineDialog from "./game/getKlineDialog"
import tradeDialog from "./game/tradeDialog"
import readmeDialog from "./game/readmeDialog"
import settleDialog from "./game/settleDialog"

export default {
  name: "stock-game",
  components: {
    VueKline,
    getKlineDialog,
    tradeDialog,
    readmeDialog,
    settleDialog
  },
  data() {
    return {
      meg: "first vue-cli test, welcome you coming",
      limit_uo_data: [],
      limit_index: 0,
      klineParams: {
        width: 1200,
        height: 600,
        theme: "light",
        language: "zh-cn",
        ranges: ["1w", "1d", "line"],
        symbol: "",
        symbolName: "",
        intervalTime: 50000,
        depthWidth: 50,
        count: 1
      },
      klineData: {
        success: true,
        data: {
          lines: [
            [0, 1.11, 1.11, 1.11, 1.11, 0],
          ]
        }
      },
      KlineDialogVisible: false,
      tradeDialogVisible: false,
      readmeDialogVisible: false,
      settleDialogVisible: false,
      rawData: {},
      newList: [],
      position: 250,
      priceStart: null,
      priceNow: null,
      tradeCount: 0,
      profitRate: 0,
    };
  },
  mounted() {
    const height = document.body.clientHeight
    const width = document.body.clientWidth
    this.klineParams.height = height - 60
    this.klineParams.width = width - 2
    if (localStorage.getItem('limit_index') !== null) {
      this.limit_index = localStorage.getItem('limit_index') * 1
    }
    this.pressEnter()
    this.get_limit_uo_data();
    setTimeout(() => {
      this.$refs.settleDialog.init(this.tradeCount, change, this.profitRate)
    }, 200)
    //this.handleRawData(data)
  },
  methods: {
    get_kline_data(stock_code) {
      console.error('get_kline_data', stock_code);
      axios({
        url: "/api/common/kline/list?stock_code=" + stock_code,
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        method: 'get',
        data: {age: 30}
      }).then((res) => {
        console.log(res);
        this.kline_data = res.data.data
        this.handleRawData(this.kline_data)
      }).catch((err) => {
        console.log(err)
      })
    },
    get_limit_uo_data() {
      axios({
        url: "/api/common/history_limit_up/list",
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        method: 'get',
        data: {age: 30}
      }).then((res) => {
        console.error(res);
        this.limit_uo_data = res.data.data
        this.get_kline_data(this.limit_uo_data[this.limit_index].stock_code);
      }).catch((err) => {
        console.log(err)
      })
    },
    formatDate(timestampOrDate, fmt) {
      if (!timestampOrDate) {
        return '';
      }

      let date = null;
      // Step 1: 如果是非时间戳，转化为时间戳
      if (typeof timestampOrDate === 'object') {
        // 传进来的是一个时间 new Date() 对象
        date = timestampOrDate;
      } else if (!/^\d+$/.test(timestampOrDate)) {
        // 把-转化成 / 避免IOS时间问题
        console.error('timestampOrDate', timestampOrDate);
        date = new Date((timestampOrDate + '').replace(/-/gi, '/'));
      } else {
        // 时间戳
        date = new Date(timestampOrDate);
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }

      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'H+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds() // 毫秒
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(o[k].toString().length));
        }
      }
      return fmt;
    },
    handleRawData(data) {
      this.rawData = data
      this.position = 250
      if (this.rawData.length > 0) {
        this.newList = this.rawData.map(function (item) {
          let time = new Date(item.start_time) * 1;
          let open = item.open;
          let high = item.high;
          let low = item.low;
          let close = item.close;
          let volume = item.volume;
          var newItem = [time, open, high, low, close, volume]
          return newItem
        })
        let start_date = this.limit_uo_data[this.limit_index].date;
        this.newList.forEach((item, index) => {
          let item_date = this.formatDate(new Date(item[0]), 'yyyy-MM-dd')

          if (start_date === item_date) {
            this.position = index;
            console.error(item_date, this.position);
          }
        })
        this.klineData.data.lines = this.newList.slice(0, this.position + 1)
        console.error(this.klineData)
        this.updateDisplay()
        // 重置交易信息
        // this.$nextTick(() => {
        //   this.$refs.tradeDialog.reset()
        // })
        const arr = this.klineData.data.lines
        this.priceStart = arr[arr.length - 1][4]
        this.tradeCount = 0
      } else {
        this.$message.error('数据有问题')
      }
    },
    handleRateData(data) {
      this.profitRate = data
    },
    // dialog handle
    KlineDialogHandle() {
      this.limit_index++;
      console.error(this.limit_index, this.limit_uo_data);
      localStorage.setItem('limit_index', this.limit_index)
      this.get_kline_data(this.limit_uo_data[this.limit_index].stock_code);
    },
    tradeDialogHandle() {
      this.tradeDialogVisible = true
      this.$nextTick(() => {
        this.$refs.tradeDialog.init(this.priceNow)
      })
    },
    readmeDialogHandle() {
      this.readmeDialogVisible = true
      this.$nextTick(() => {
        this.$refs.readmeDialog.init()
      })
    },
    settleDialogHandle() {
      this.settleDialogVisible = true
      const change = ((this.priceNow / this.priceStart - 1) * 100).toFixed(1)
      this.$nextTick(() => {
        this.$refs.tradeDialog.sendProfitRate(this.priceNow)
      })
      this.$nextTick(() => {
        this.$refs.settleDialog.init(this.tradeCount, change, this.profitRate)
      })
    },
    //
    pressEnter() {
      document.onkeydown = (e) => {
        if (e.keyCode == 39) {
          console.log('enter')
          console.log(this.passOne())
        }
      }
    },
    passOne() {
      if (this.newList.length > this.position) {
        this.position += 1
        this.tradeCount += 1
        this.klineData.data.lines = this.newList.slice(0, this.position + 1)
        this.updateDisplay()
      } else {
        this.$message.error('K线已到尽头')
      }
    },
    backOne() {
      if (this.newList.length > this.position) {
        this.position -= 1
        this.tradeCount -= 1
        this.klineData.data.lines = this.newList.slice(0, this.position + 1)
        this.updateDisplay()
      } else {
        this.$message.error('K线已到尽头')
      }
    },
    updateDisplay() {
      const newData = this.klineData.data.lines
      var chart = new Chart()
      chart.updateDataAndDisplay(newData)
      // chart.updateDataAndDisplay(newData) //不优雅的解决一个vue-kline自带的bug
      this.getNewPrice()
    },
    getNewPrice() {
      const arr = this.klineData.data.lines
      this.priceNow = arr[arr.length - 1][4]
      // console.log(this.priceNow)
    }
  }
}
</script>
